<template>
  <div>
    <Row>
      <Col span="24">
        <Card class="margin-bottom-10">
          <Form inline>
            <FormItem class="margin-bottom-0">
              <Select
                v-model="searchConf.game_hash"
                filterable
                remote
                :remote-method="getGameName"
                style="width:260px"
                placeholder='请选择游戏'
                :loading="nameLoading"
              >
                <Option v-for="(option, index) in gameNameOption" :value="option.value" :key="index">{{option.label}}</Option>
              </Select>
            </FormItem>
            <FormItem class="margin-bottom-0">
              <Button type="primary" @click="search">{{ $t('find_button') }}/{{ $t('refresh_button') }}</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>
    <Row>
      <Col span="24">
        <Card>
          <div class="margin-bottom-15">
            <Button type="primary" v-has="'Mail/add'" @click="alertAdd" icon="md-add">{{ $t('add_button') }}</Button>
          </div>
          <div>
            <Table :loading="listLoading" :columns="columnsList" :data="tableData" border disabled-hover />
          </div>
          <div class="margin-top-15" style="text-align: center">
            <Page :total="tableShow.listCount" :current="tableShow.currentPage"
                  :page-size="tableShow.pageSize" @on-change="changePage"
                  @on-page-size-change="changeSize" show-elevator show-sizer show-total />
          </div>
        </Card>
      </Col>
    </Row>
    <Modal v-model="modalSetting.show" width="668" :styles="{top: '30px'}" @on-visible-change="doCancel">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert" />
        <span>{{formItem.id ? '编辑' : '新增'}}邮件</span>
      </p>
      <Form ref="myForm" :rules="ruleValidate" :model="formItem" :label-width="100">
        <Row>
          <Col span="12">
            <FormItem label="目标游戏" prop="game_hash">
              <Select
                v-model="formItem.game_hash"
                filterable
                style="width: 100%"
                placeholder='请选择游戏'
                :disabled="modalSetting.index !== 0"
              >
                <Option v-for="(option, index) in gameNameOption" :value="option.value" :key="index">{{option.label}}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="发送对象" prop="type">
              <Select v-model="formItem.type" style="width: 100%" :disabled="modalSetting.index !== 0">
                <Option :value="1">全体成员</Option>
                <Option :value="2">指定成员</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="送达角色" prop="hero_id">
              <Select v-model="formItem.hero_id" style="width: 100%" :disabled="modalSetting.index !== 0">
                <Option :value="0">全部角色</Option>
                <!-- <Option :value="1001">驭剑者</Option> -->
                <Option :value="1002">剑影（狐狸）</Option>
                <Option :value="1004">炎刃（狼）</Option>
                <Option :value="1005">灵剑师（虎）</Option>
                <Option :value="1006">双弩游侠（猞猁）</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="目标OpenId" prop="openid" v-if="formItem.type === 2">
          <Input v-model="formItem.openid" type="textarea" :autosize="{minRows: 2,maxRows: 5}" :disabled="modalSetting.index !== 0" />
        </FormItem>
        <Row>
          <Col span="12">
            <FormItem label="邮件名称" prop="title">
              <Input v-model="formItem.title" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="发送人" prop="send">
              <Input v-model="formItem.send" />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="发送时间" prop="start_time">
              <DatePicker
                type="datetime"
                :transfer="true"
                format="yyyy-MM-dd HH:mm:ss"
                v-model="startTime"
                style="width: 100%;"
              />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="有效天数" prop="expire">
              <Input v-model="formItem.expire">
                <span slot="append">天</span>
              </Input>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="邮件描述" prop="info">
          <Input v-model="formItem.info" type="textarea" :autosize="{minRows: 5,maxRows: 8}" />
        </FormItem>
        <FormItem label="邮件附件" prop="reward">
          <Input v-model="formItem.reward" type="textarea" :autosize="{minRows: 5,maxRows: 8}" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel" class="margin-right-10">取消</Button>
        <Button type="primary" @click="submit" :loading="modalSetting.loading">确定</Button>
      </div>
    </Modal>

    <Modal v-model="keySetting.show" width="996" :styles="{top: '30px'}">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert" />
        <span>领取情况</span>
      </p>
      <div class="margin-bottom-15">
        <Input v-model="buildKeyInfo.openid" placeholder="请输入openid" class="margin-right-10" style="width: 200px" />
        <Button type="primary" @click="getKeyList">查询</Button>
      </div>
      <div>
        <Table :loading="keySetting.listLoading" :columns="keyColumnsList" :data="keyData" border disabled-hover />
      </div>
      <div slot="footer" style="text-align: center">
        <Page :total="keyShow.listCount" :current="keyShow.currentPage" :page-size="keyShow.pageSize"
              @on-change="changeKeyPage" @on-page-size-change="changeKeySize" show-elevator show-sizer show-total />
      </div>
    </Modal>
  </div>
</template>
<script>
import { getList, add, changeStatus, log } from '@/api/game-mail'
import { getChoose } from '@/api/game-manager'
const keyButton = (vm, h, currentRow, index) => {
  if (vm.buttonShow.key) {
    return h('Button', {
      props: {
        type: 'primary'
      },
      style: {
        margin: '0 5px'
      },
      on: {
        'click': () => {
          vm.buildKeyInfo.mail_id = currentRow.id
          vm.buildKeyInfo.game_hash = currentRow.game_hash
          vm.getKeyList()
          vm.keySetting.show = true
          vm.keySetting.index = index
        }
      }
    }, '领取人')
  }
}
export default {
  name: 'operate-mail',
  data () {
    return {
      typeList: [],
      nameLoading: false,
      gameNameOption: [],
      gameShow: {},
      columnsList: [
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center'
        },
        {
          title: '邮件名称',
          align: 'center',
          key: 'title',
          minWidth: 120
        },
        {
          title: '发送对象',
          align: 'center',
          minWidth: 120,
          tooltip: true,
          render: (h, params) => {
            if (params.row.openid) {
              return h('span', '指定玩家')
            } else {
              return h('span', '全体成员')
            }
          }
        },
        {
          title: '邮件描述',
          align: 'center',
          key: 'info',
          tooltip: true,
          minWidth: 120
        },
        {
          title: '邮件附件',
          align: 'center',
          key: 'reward',
          tooltip: true,
          minWidth: 120
        },
        {
          title: '所属游戏',
          align: 'center',
          render: (h, params) => {
            return h('span', this.gameShow[params.row.game_hash])
          },
          width: 200
        },
        {
          title: '邮件状态',
          align: 'center',
          width: 130,
          render: (h, params) => {
            let vm = this
            return h('i-switch', {
              attrs: {
                size: 'large'
              },
              props: {
                'true-value': 1,
                'false-value': 0,
                value: params.row.status,
                disabled: !vm.buttonShow.changeStatus || params.row.status === 0
              },
              on: {
                'on-change': function (status) {
                  changeStatus(status, params.row.id, params.row.game_hash).then(response => {
                    vm.$Message.success(response.data.msg)
                    vm.getList()
                  })
                }
              }
            }, [
              h('span', {
                slot: 'open'
              }, vm.$t('open_choose')),
              h('span', {
                slot: 'close'
              }, vm.$t('close_choose'))
            ])
          }
        },
        {
          title: '创建时间',
          align: 'center',
          key: 'created_at',
          width: 170
        },
        {
          title: '操作',
          align: 'center',
          width: 150,
          render: (h, params) => {
            return h('div', [
              keyButton(this, h, params.row, params.index)
            ])
          }
        }
      ],
      tableData: [],
      tableShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      searchConf: {
        game_hash: ''
      },
      modalSetting: {
        show: false,
        loading: false,
        index: 0
      },
      startTime: '',
      formItem: {
        game_hash: '',
        openid: '',
        type: 2,
        expire: 30,
        hero_id: 0,
        title: '',
        info: '',
        send: '系统',
        reward: '',
        start_time: '',
        id: 0
      },
      ruleValidate: {
        game_hash: [
          { required: true, message: '请选择游戏', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '邮件名称不能为空', trigger: 'blur' }
        ],
        send: [
          { required: true, message: '发送人不能为空', trigger: 'blur' }
        ]
      },
      buttonShow: {
        edit: true,
        key: true,
        changeStatus: true
      },
      keySetting: {
        show: false,
        loading: false,
        listLoading: false,
        index: 0
      },
      keyColumnsList: [
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center'
        },
        {
          title: '所属游戏',
          align: 'center',
          render: (h, params) => {
            return h('span', this.gameShow[params.row.game_hash])
          },
          width: 200
        },
        {
          title: '使用者',
          align: 'center',
          key: 'openid',
          render: (h, params) => {
            if (params.row.openid) {
              return h('span', params.row.openid)
            } else {
              return h('span', '-')
            }
          },
          minWidth: 260
        },
        {
          title: '使用角色ID',
          align: 'center',
          key: 'role_id',
          render: (h, params) => {
            if (params.row.role_id) {
              return h('span', params.row.role_id)
            } else {
              return h('span', '-')
            }
          },
          minWidth: 160
        },
        {
          title: '邮件名称',
          align: 'center',
          key: 'title',
          tooltip: true,
          width: 150
        },
        {
          title: '邮件附件',
          align: 'center',
          key: 'reward',
          tooltip: true,
          minWidth: 120
        },
        {
          title: '邮件状态',
          align: 'center',
          width: 130,
          render: (h, params) => {
            if (params.row.status === 1) {
              return h('span', '未领取')
            } else if (params.row.status === 4) {
              return h('span', '已失效')
            } else {
              return h('span', '已领取')
            }
          }
        },
        {
          title: '兑换时间',
          align: 'center',
          render: (h, params) => {
            if (params.row.status === '1') {
              return h('span', '未领取')
            } else if (params.row.status === '4') {
              return h('span', '已失效')
            } else {
              return h('span', params.row.updated_at)
            }
          },
          width: 200
        }
      ],
      keyData: [],
      keyShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      buildKeyInfo: {
        openid: '',
        mail_id: '',
        game_hash: ''
      },
      listLoading: false
    }
  },
  created () {
    let vm = this
    vm.getList()
    vm.getGameName()
    vm.hasRule('Mail/changeStatus').then(res => {
      vm.buttonShow.changeStatus = res
    })
  },
  methods: {
    alertAdd () {
      this.getGameName()
      this.modalSetting.show = true
      this.modalSetting.index = 0
    },
    getKeyList () {
      let vm = this
      vm.keySetting.listLoading = true
      log({
        page: vm.keyShow.currentPage,
        size: vm.keyShow.pageSize,
        mail_id: vm.buildKeyInfo.mail_id,
        game_hash: vm.buildKeyInfo.game_hash,
        openid: vm.buildKeyInfo.openid
      }).then(response => {
        vm.keyData = response.data.data.list
        vm.keyShow.listCount = response.data.data.count
        vm.keySetting.listLoading = false
      })
    },
    changeKeyPage (page) {
      this.keyShow.currentPage = page
      this.getKeyList()
    },
    changeKeySize (size) {
      this.keyShow.pageSize = size
      this.getKeyList()
    },
    getGameName (value) {
      if (!this.gameNameOption.length) {
        getChoose({
          keyword: value
        }).then(response => {
          this.gameNameOption = response.data.data.list
          this.gameNameOption.forEach(i => {
            this.gameShow[i.value] = i.label
          })
        })
      }
    },
    submit () {
      let vm = this
      this.$refs['myForm'].validate((valid) => {
        if (valid) {
          if (vm.startTime) {
            vm.modalSetting.loading = true
            vm.formItem.start_time = Date.parse(vm.startTime) / 1000

            if (vm.formItem.type === 1) {
              vm.formItem.openid = ''
            }
            if (vm.formItem.id === 0) {
              add(vm.formItem).then(response => {
                vm.$Message.success(response.data.msg)
                vm.getList()
                vm.cancel()
              }).catch(() => {
                vm.modalSetting.loading = false
              })
            } else {
              edit(vm.formItem).then(response => {
                vm.$Message.success(response.data.msg)
                vm.getList()
                vm.cancel()
              }).catch(() => {
                vm.modalSetting.loading = false
              })
            }
          } else {
            this.$Notice.error({
              title: '发送时间不能为空'
            })
          }
        }
      })
    },
    cancel () {
      this.modalSetting.show = false
    },
    doCancel (data) {
      if (!data) {
        this.formItem.id = 0
        this.formItem.type = 1
        this.$refs['myForm'].resetFields()
        this.modalSetting.loading = false
        this.modalSetting.index = 0
      }
    },
    changePage (page) {
      this.tableShow.currentPage = page
      this.getList()
    },
    changeSize (size) {
      this.tableShow.pageSize = size
      this.getList()
    },
    search () {
      this.tableShow.currentPage = 1
      this.getList()
    },
    getList () {
      let vm = this
      let params = {
        page: vm.tableShow.currentPage,
        size: vm.tableShow.pageSize,
        ...vm.searchConf
      }
      vm.listLoading = true
      getList(params).then(response => {
        vm.tableData = response.data.data.list
        vm.tableShow.listCount = response.data.data.count
        vm.listLoading = false
      })
    }
  }
}
</script>
